package com.cuhk.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.cuhk.common.to.SkuStockTo;
import com.cuhk.common.utils.R;
import com.cuhk.gulimall.product.entity.*;
import com.cuhk.gulimall.product.feign.WareFeignService;
import com.cuhk.gulimall.product.service.*;
import com.cuhk.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuhk.common.utils.PageUtils;
import com.cuhk.common.utils.Query;

import com.cuhk.gulimall.product.dao.SkuInfoDao;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuInfoDescServiceImpl spuInfoDescService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)) {
            wrapper.and((w) -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId)) {
            if(!"0".equalsIgnoreCase(catelogId)) {
                wrapper.eq("catalog_id", catelogId);
            }
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId)) {
            if(!"0".equalsIgnoreCase(brandId)) {
                wrapper.eq("brand_id", brandId);
            }
        }

        // sku价格区间
        // 包括最小值min和最大值max
        String min = (String) params.get("min");
        if(StringUtils.isNotBlank(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if(StringUtils.isNotBlank(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {}
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return skuInfoDao.selectList(wrapper);
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();

        // 1. 开启异步任务task1 --> 查询SkuInfoEntity
        CompletableFuture<SkuInfoEntity> task1 = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = skuInfoDao.selectById(skuId);
            skuItemVo.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        // 2. 开启异步任务task2 --> 查询sku库存信息
        CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
            R res = wareFeignService.getSkuHasStock(skuId);
            if(res.get("data") != null) {
                SkuStockTo to = res.getData(new TypeReference<SkuStockTo>() {});
                skuItemVo.setHasStock(to.getValidStock());
            }
            else {
                skuItemVo.setHasStock(false);
            }
        }, threadPoolExecutor);

        // 3. 开启异步任务task3 --> 查询sku图片信息
        CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.getSkuImagesBySkuId(skuId);
            skuItemVo.setSkuImages(skuImages);
        }, threadPoolExecutor);

        // 4. 等待task1的执行结果，而后调用线程池中另一个线程, 开启任务5, 查询spuInfoDesc信息
        CompletableFuture<Void> task4 = task1.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getSpuInfoDescById(spuId);
            spuInfoDesc.fillDescriptionList();
            skuItemVo.setSpuInfoDesc(spuInfoDesc);
        }, threadPoolExecutor);

        // 5. 等待task1的执行结果，而后调用线程池中的一个线程，开启任务5，查询sku的销售属性
        CompletableFuture<Void> task5 = task1.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(spuId);
            skuItemVo.setSaleAttrs(skuItemSaleAttrVos);
        }, threadPoolExecutor);

        // task6 --> 查询spu的规格属性
        CompletableFuture<Void> task6 = task1.thenAcceptAsync((res) -> {
            Long spuId = res.getSpuId();
            SpuInfoEntity spuInfoEntity = spuInfoService.getById(spuId);
            // 利用三级分类id查询属性分组表
            Long cateLogId = spuInfoEntity.getCatalogId();
            skuItemVo.setGroupAttrs(attrGroupService.getSpuItemAttrGroupVoByIds(cateLogId, spuId));
        }, threadPoolExecutor);

        // 等待所有任务运行完毕
        CompletableFuture[] tasks = new CompletableFuture[]{task1, task2, task3, task4, task5, task6};
        CompletableFuture.allOf(tasks).join();

        return skuItemVo;
    }

}